<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="单号" prop="danhao">
        <el-input
          v-model="queryParams.danhao"
          placeholder="请输入入库单号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="入库类型" prop="rukuType">
        <el-select v-model="queryParams.rukuType" placeholder="请选择入库类型" clearable>
          <el-option
            v-for="dict in dict.type.ruku_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
            :disabled="dict.value == 0 || dict.value == 1"
          />
        </el-select>
      </el-form-item>
      <!--<el-form-item label="仓库编号" prop="stockId">
        <el-input
          v-model="queryParams.stockId"
          placeholder="请输入仓库编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>-->

      <el-form-item label="入库仓库" prop="stockId">
        <el-select clearable  v-model="queryParams.stockId" placeholder="请选择入库仓库" clearable>
          <el-option
            v-for="dict in warehouseinfo"
            :key="dict.value"
            :label="dict.label"
            :value="parseInt(dict.value)"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="入库日期" prop="rukuDate">
        <el-date-picker clearable
                        v-model="queryParams.rukuDate"
                        type="date"
                        value-format="yyyy-MM-dd"
                        placeholder="请选择入库日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['business:rukumain:add']"
        >增加入库</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
         <el-button
           type="success"
           plain
           icon="el-icon-edit"
           size="mini"
           :disabled="single"
           @click="handleUpdate"
           v-hasPermi="['business:rukumain:edit']"
         >修改</el-button>
       </el-col>-->
      <!-- <el-col :span="1.5">
         <el-button
           type="danger"
           plain
           icon="el-icon-delete"
           size="mini"
           :disabled="multiple"
           @click="handleDelete"
           v-hasPermi="['business:rukumain:remove']"
         >删除</el-button>
       </el-col>-->
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['business:rukumain:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="rukumainList" @selection-change="handleSelectionChange">
      <!--
            <el-table-column type="selection" width="55" align="center" />
      -->
      <el-table-column width="150" label="入库单号" align="center" prop="danhao">
        <template scope="scope">
          <div style="cursor:pointer;text-decoration:underline;color: blue" class="danhao" @click="handleRuKuChaKan(scope.row)">{{ scope.row.danhao }}</div>
        </template>
      </el-table-column>
      <el-table-column label="入库类型" width="90" align="center" prop="rukuType">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.ruku_type" :value="scope.row.rukuType"/>
        </template>
      </el-table-column>
      <el-table-column label="仓库编号" align="center" prop="stockId" />
      <el-table-column label="入库仓库" align="center" prop="stockName" />
      <el-table-column label="入库总数量" width="100" align="center" prop="totalNum" />
      <el-table-column label="入库总额" align="center" prop="totalPrice" />
      <el-table-column label="入库日期" align="center" prop="rukuDate" width="100">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.rukuDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="生产日期" align="center" prop="scDate" width="150">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.scDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="批次" width="100" align="center" prop="lot" />
      <el-table-column label="工人姓名" align="center" prop="grName" />
      <el-table-column label="班组" align="center" prop="bz" />
      <el-table-column label="状态" align="center" prop="state">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.crk_state" :value="scope.row.state"/>
        </template>
      </el-table-column>
      <el-table-column label="经办人" align="center" prop="createBy" />
      <el-table-column label="创建时间" align="center" prop="createTime" width="180"/>
      <!--
            <el-table-column label="关联单号" align="center" prop="gldanhao" width="150"/>
      -->
      <el-table-column show-overflow-tooltip label="备注" align="center" prop="remark" />
      <el-table-column label="操作"  width="150" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['business:rukumain:edit']"
            v-if="scope.row.state != 1 "
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-circle-check"
            v-if="scope.row.state != 1"
            @click="handleRuKuSelect(scope.row)"
            v-hasPermi="['business:rukumain:zhixing']"
          >执行</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-circle-close"
            @click="handleDelete(scope.row)"
            v-if="scope.row.state != 1"
          >撤销</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />



    <el-dialog :close-on-click-modal="false" :title="title" :visible.sync="open" width="1300px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" style="margin-top: -20px" label-width="120px">
        <el-row>
          <el-col :span="8">
            <el-form-item label="入库类型" prop="rukuType">
              <el-select v-model="form.rukuType" placeholder="请选择入库类型" clearable>
                <el-option
                  v-for="dict in dict.type.ruku_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="parseInt(dict.value)"
                  :disabled="dict.value == 0 || dict.value == 1"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="入库日期" prop="rukuDate">
              <el-date-picker clearable
                              v-model="form.rukuDate"
                              type="date"
                              value-format="yyyy-MM-dd"
                              placeholder="请选择入库日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="入库仓库" prop="stockId">
              <el-select @change="getCangku"  v-model="form.stockId" placeholder="请选择入库仓库" clearable>
                <el-option
                  v-for="dict in warehouseinfo"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
         <!-- <el-col :span="8">
            <el-form-item label="供货单位" prop="supplyId">
              <el-select style="width: 100%" @change="getSupply" filterable v-model="form.supplyId" placeholder="请选择供货单位" >
                <el-option
                  v-for="dict in supplyOptions"
                  :key="dict.id"
                  :label="dict.supplyName"
                  :value="parseInt(dict.id)"
                />
              </el-select>
            </el-form-item>
          </el-col>-->
          <el-col :span="8">
            <el-form-item label="生产日期" prop="scDate">
              <el-date-picker clearable
                              v-model="form.scDate"
                              type="date"
                              value-format="yyyy-MM-dd"
                              placeholder="请选择生产日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="工人姓名" prop="grName">
              <el-input v-model="form.grName" placeholder="请输入工人姓名" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="班组" prop="bz">
              <el-input v-model="form.bz" placeholder="请输入班组" />
            </el-form-item>
          </el-col>
        </el-row>
     <!--   <el-row>
          <el-col :span="8">
            <el-form-item label="收票日期" prop="piaoDate">
              <el-date-picker clearable
                              v-model="form.piaoDate"
                              type="date"
                              value-format="yyyy-MM-dd"
                              placeholder="请选择收票日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="票号" prop="piaoNum">
              <el-input v-model="form.piaoNum" placeholder="请输入票号" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="优惠金额" prop="yhTotalPrice">
              <el-input v-model="form.yhTotalPrice" placeholder="请输入优惠金额" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="支付方式" prop="szFs">
              <el-select v-model="form.szFs" placeholder="请选择入库类型" clearable>
                <el-option
                  v-for="dict in dict.type.sz_fs"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="银行账户" prop="zhNum">
              <el-input v-model="form.zhNum" placeholder="请输入银行账户" />
            </el-form-item>
          </el-col>
        </el-row>-->
        <el-row>
          <el-col :span="12">
            <el-form-item label="备注" prop="remark">
              <el-input style="width: 500px"  type="textarea" v-model="form.remark" placeholder="请输入备注" />
              <el-input v-model="form.rukuFlag" v-show="false"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <RukuScDetail ref="rukuScDetail"></RukuScDetail>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">提 交</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog :close-on-click-modal="false" :title="rukuSelect.title" :visible.sync="rukuSelect.open" width="1000px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" style="margin-top: -20px" label-width="80px">
        <!--      <el-row>
                <el-col :span="8">
                  <el-form-item label="入库类型" prop="rukuType">
                    <el-select disabled  v-model="form.rukuType" placeholder="请选择入库类型" clearable>
                      <el-option
                        v-for="dict in dict.type.ruku_type"
                        :key="dict.value"
                        :label="dict.label"
                        :value="parseInt(dict.value)"
                        :disabled="dict.value == 0"
                      />
                    </el-select>
                  </el-form-item>
                  <el-col :span="8">
                    <el-form-item  label="入库日期" prop="rukuDate">
                      <el-date-picker readonly clearable
                                      v-model="form.rukuDate"
                                      type="date"
                                      value-format="yyyy-MM-dd"
                                      placeholder="出库日期">

                      </el-date-picker>
                    </el-form-item>
                  </el-col>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="仓库" prop="stockId">
                    <el-select disabled @change="getCangku"  v-model="form.stockId" placeholder="请选择入库仓库" clearable>
                      <el-option
                        v-for="dict in warehouseinfo"
                        :key="dict.value"
                        :label="dict.label"
                        :value="dict.value"
                      />
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="12">
                  <el-form-item label="备注" prop="remark">
                    <el-input readonly style="width: 500px"  type="textarea" v-model="form.remark" placeholder="" />
                  </el-form-item>
                </el-col>
              </el-row>-->
        <el-row>
          <el-col :span="24">
            <cpRukuSelect :rowData ="this.rowData" ref="cpRukuSelect"></cpRukuSelect>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" v-show="rukuSelect.isShow" @click="submitZx">执 行</el-button>
        <el-button @click="rukuSelect.open = false">取 消</el-button>
      </div>
    </el-dialog>
    <!--    ruku单详情-->
    <el-dialog :close-on-click-modal="false" :title="rukuTitle" :visible.sync="rukuOpen"  width="1350px" append-to-body>
      <el-table v-loading="rukuLoading" :data="rukuList">
        <el-table-column label="入库单号" width="150" align="center" prop="danhao"  />
        <el-table-column label="入库日期" width="150" align="center" prop="rukuDate"  />
        <el-table-column label="物料名称" width="150" align="center" prop="itemName"  />
        <el-table-column label="物料编号" width="100" align="center" prop="itemId"  />
        <el-table-column label="大类" width="100" align="center" prop="className"  />
        <el-table-column label="规格" width="100" align="center" prop="spec"  />
        <el-table-column label="单位" width="80" align="center" prop="unit"  />
        <el-table-column label="入库数量" width="80" align="center" prop="rukuNum"  />
        <el-table-column label="仓库" width="120" align="center" prop="stockName"  />
        <el-table-column label="供应商" width="120" align="center" prop="supplyName"  />
        <el-table-column label="经办人" width="150" align="center" prop="createBy"  />
      </el-table>
    </el-dialog>
  </div>
</template>

<script>
  import { listRukumain, getRukumain, delRukumain, addRukumain, updateRukumain,zhixingRuku } from "@/api/business/rukumain";
  import { getListWarehouseinfo } from "@/api/base/warehouseinfo";
  import { listRukudetail } from "@/api/business/rukudetail";
  import { getLiSupplier} from "@/api/supplychain/supplier";

  import RukuScDetail from "./rukuScDetail";
  import cpRukuSelect from "./cpRukuSelect";
  export default {
    components: {
      RukuScDetail,
      cpRukuSelect
    },
    name: "RukuScMain",
    dicts: ['ruku_type','crk_state','sz_fs'],
    data() {
      return {
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        danhaos: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        rowData:{},
        // 入库任务表格数据
        rukumainList: [],
        warehouseinfo:[],
        //供应商字典
        supplyOptions: [],
        // 弹出层标题
        title: "",
        rukuTitle:'',
        rukuOpen:false,
        rukuList:[],
        rukuLoading:true,
        // 是否显示弹出层
        open: false,
        openInfo: false,
        rukuSelect:{
          // 是否显示弹出层（
          open: false,
          // 弹出层标题
          title: "",
          isShow:false,
        },
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          rukuType: null,
          stockId: null,
          stockName: null,
          rukuDate: null,
          danhao:null,
          rukuFlag:2,
        },
        queryParams2: {
          pageNum: 1,
          pageSize: 10,
          mainId: null,
          rukuNum: null,
          rukuDate: null,
          itemName: null,
          itemId: null,
          supplyId: null,
          supplyName: null,
          stockId: null,
          stockName: null,
          price: null,
          classId: null,
          className: null,
          danhao:null,
        },
        // 表单参数
        form: {
          infoList:[]
        },
        // 表单校验
        rules: {
          stockId: [
            { required: true, message: "请选择入库仓库", trigger: "blur" }
          ],
          supplyId: [
            { required: true, message: "请选择供货单位", trigger: "blur" }
          ],
          szFs: [
            { required: true, message: "请选择支付方式", trigger: "blur" }
          ],
          rukuType: [
            { required: true, message: "请选择入库类型", trigger: "blur" }
          ],
          rukuDate: [
            { required: true, message: "请选择入库日期", trigger: "blur" }
          ],

        }
      };
    },
    created() {
      this.getList();
      getListWarehouseinfo().then(response => {
        this.warehouseinfo = response.data;
      });
      getLiSupplier().then(response => {
        this.supplyOptions = response.data;
      });
    },
    methods: {
      /** 查询入库任务列表 */
      getList() {
        this.loading = true;
        listRukumain(this.queryParams).then(response => {
          this.rukumainList = response.rows;
          this.total = response.total;
          this.loading = false;
        });
      },
      // 点击订单号展示详情
      rowClickInfo(row){
        this.queryParams2.danhao = row.danhao
        listRukudetail(this.queryParams2).then(res=>{
          this.rukuList = res.rows
          console.log(this.rukuList)
        })
        this.rukuTitle = '入库单详情'
        this.rukuOpen = true
        this.rukuLoading = false
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {
          id: null,
          rukuType: null,
          stockId: null,
          stockName: null,
          rukuDate:  new Date(),
          createBy: null,
          createTime: null,
          updateBy: null,
          updateTime: null,
          remark: null,
          supplyName: null,
          supplyId: null,
          ghDate: null,
          ghCarNum: null,
          piaoNum: null,
          piaoDate: null,
          totalPrice: null,
          zhNum: null,
          szFs: null,
          lot: null,
          zfTotalPrice: null,
          yhTotalPrice: 0,
          //生产入库
          rukuFlag: 2,
          scDate: null,
          grName: null,
          bz: null,
        };
        this.resetForm("form");
      },

      //展示子表
      rowClick(row){
        let id = row.id;
        this.reset();
        this.openInfo = true;
        this.title = "入库详情";
      },
      getCangku(value){
        let selectedName = {};
        selectedName = this.warehouseinfo.find((item)=>{
          return item.value === value;
          //筛选出匹配数据，是对应数据的整个对象
        });
        this.form.stockName=selectedName.label;
      },

      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.id)
        this.danhaos = selection.map(item => item.danhao)
        this.single = selection.length!==1
        this.multiple = !selection.length
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        this.open = true;
        this.title = "添加生产入库单";
        this.form.rukuFlag=2;
        setTimeout(() => {
          this.$refs.rukuScDetail.listReset();
        }, 10);
      },
      /** 入库单查看 */
      handleRuKuChaKan(row) {
        console.log(row,'rowwwww')
        this.rowData = row
        this.reset();
        const id = row.id || this.ids
        const danhaos = row.danhao || this.danhaos
        getRukumain(id).then(response => {
          this.form = response.data;
          this.rukuSelect.open = true;
          this.rukuSelect.isShow=false;
          this.rukuSelect.title = "";
          setTimeout(() => {
            this.$refs.cpRukuSelect.getRkSelectList(danhaos.toString());
          }, 5);
        });
      },
      /*执行入库*/
      handleRuKuSelect(row) {
        this.reset();
        const id = row.id || this.ids
        const danhaos = row.danhao || this.danhaos
        getRukumain(id).then(response => {
          if(response.data.stockId==null||response.data.stockId==""||response.data.stockId==undefined){
            this.$modal.alertWarning("请选择仓库！");
            return;
          }
          this.form = response.data;
          this.rukuSelect.open = true;
          this.rukuSelect.isShow=true;
          this.rukuSelect.title = "生产入库单执行入库";
          setTimeout(() => {
            this.$refs.cpRukuSelect.getRkSelectList(danhaos.toString());
          }, 5);
        });
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset();
        const id = row.id || this.ids
        const danhaos = row.danhao || this.danhaos
        getRukumain(id).then(response => {
          this.form = response.data;
          this.form.rukuFlag=2;
          this.open = true;
          this.title = "修改生产入库单";
          setTimeout(() => {
            this.$refs.rukuScDetail.getRkInfoList(danhaos.toString());
          }, 5);
        });
      },
      /*执行入库*/
      submitZx(){
        const danhao=this.form.danhao;
        this.$modal.confirm('是否确认执行入库单为'+danhao+"吗?").then(function() {
          return zhixingRuku(danhao);
        }).then(() => {
          this.rukuSelect.open=false;
          this.getList();
          this.$modal.alertSuccess("入库成功");
        }).catch(() => {});
      },
      getSupply(value){
        let obj = {};
        obj = this.supplyOptions.find((item) => { //companyListAdd就是上面遍历的数组的数据源
          return item.id === value; //筛选出匹配的数据
        })
        this.form.supplyName = obj.supplyName;
      },
      /** 提交按钮 */
      submitForm() {
        let rukudetailList= this.$refs.rukuScDetail.rukudetailList;
        this.form.infoList=rukudetailList;
        if(rukudetailList.length==0){
          this.$modal.alertWarning('请选择物料')
          return;
        }
        for(var i=0;i<rukudetailList.length;i++){
          if(rukudetailList[i].rukuNum==''||rukudetailList[i].rukuNum==null||rukudetailList[i].rukuNum==undefined){
            this.$modal.alertWarning('请输入库数量')
            return;
          }
          if(rukudetailList[i].unitPrice==''||rukudetailList[i].unitPrice==null||rukudetailList[i].unitPrice==undefined){
            this.$modal.alertWarning('请输入单价')
            return;
          }
        }
        this.$refs["form"].validate(valid => {
          if (valid) {
            if (this.form.id != null) {
              updateRukumain(this.form).then(response => {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              });
            } else {
              addRukumain(this.form).then(response => {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              });
            }
          }
        });
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        if(row.state=='1'){
          this.$modal.alertWarning("入库单"+danhao+"已完成无法撤销！");
          return;
        }
        const danhao = row.danhao;
        this.$modal.confirm('是否确认撤销入库单为'+danhao+"?").then(function() {
          return delRukumain(danhao);
        }).then(() => {
          this.getList();
          this.$modal.alertSuccess("撤销成功");
        }).catch(() => {});
      },
      /** 导出按钮操作 */
      handleExport() {
        this.download('business/rukumain/export', {
          ...this.queryParams
        }, `rukumain_${new Date().getTime()}.xlsx`)
      }
    }
  };
</script>
